package com.springCloud.luoqiu.service;

import com.luoqiu.entities.Payment;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.utils.FallbackMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @author 洛秋y
 * @date 2020/11/20 14:14
 */
@Service
public class PaymentService {
    public String get() {
        Payment payment = new Payment();
        payment.setId(2);
        payment.setSerial("csdfas22");
        return payment.toString();
    }

    @HystrixCommand(fallbackMethod =  "failHandler", commandProperties = {
            //超过三秒 就报异常 走备用方法
            @HystrixProperty(name = "execution.isolation.thread.timeoutMilliseconds", value = "3000")
    })
    public String fail() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    public String failHandler() {
        return "有点忙";
    }

    //=============服务熔断==============

    @HystrixCommand(fallbackMethod =  "breakerHandler", commandProperties = {
            //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            //请求次数  10次中60%失败 开启短路
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            //时间窗口期
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            //失败率达到多少断路
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
    })
    public String paymentCircuitBreaker(long id) {
        if (id < 0) {
            throw new RuntimeException("id不能小于0");
        }
        return "cici";
    }

    public String breakerHandler(long id) {
        return "id不能小于0";
    }
}
